<!--
 * @Author: yansheng 610363806@qq.com
 * @Date: 2024-06-27 22:14:20
 * @LastEditors: yansheng 610363806@qq.com
 * @LastEditTime: 2024-07-31 21:44:37
 * @FilePath: \cell-admin\src\pages\user\record\index.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<template>
  <a-row>
    <a-col :span="16">
      <ProTable
        :columns="columns"
        :data-source="activities"
        :pagination="pagination"
        @change="handleTableChange"
      >
        <template #extraL>
          <a-button
            type="primary"
            @click="openDialog('1')"
          >
            添加积分
          </a-button>
          <a-button
            type="primary"
            @click="openDialog('2')"
          >
            消费积分
          </a-button>
        </template>

        <template #bodyCell="{ column, record }">
          <template v-if="column.dataIndex === 'uid'">
            <div
              class="user-info"
              v-if="userInfo"
            >
              <img
                class="user-info-avatar"
                style=""
                :src="userInfo.avatar"
                alt=""
              />
              <div class="user-name">
                <div class="name">{{ userInfo.user_name }}</div>
                <div class="phone">{{ userInfo.phone }}</div>
              </div>
            </div>
          </template>
          <template v-if="column.dataIndex === 'deleted_at'">
            <a-tag
              color="orange"
              v-if="record.deleted_at"
            >
              已使用
            </a-tag>
            <a-tag
              v-else
              color="green"
            >
              未使用
            </a-tag>
          </template>
          <template v-if="column.dataIndex === 'operator_name'">
            {{ record.Admin.admin_name }}
          </template>

          <template v-if="column.dataIndex === 'action' && !record.deleted_at">
            <span>
              <a-popconfirm
                title="是否确认删除?"
                cancel-text="否"
                @confirm="handleDel(record)"
              >
                <template #okButton>
                  <a-button
                    :disabled="isdisabled"
                    key="submit"
                    type="primary"
                    @click="handleDel(record)"
                  >
                    {{ delText }}
                  </a-button>
                </template>
                <a @click="openPop">删除</a>
              </a-popconfirm>
            </span>
          </template>
        </template>
      </ProTable>
    </a-col>
    <a-col
      :span="8"
      style="margin-top: 40px;  padding-top: 20px; overflow-y: scroll"
    >
    <div style="font-size: 16px;font-weight: 500;">积分日志</div>
    <div style="margin: 30px 0;">温馨提示：只展示最近10条数据，点击<a @click="goMoreLog">查看更多</a></div>
      <a-timeline>
        <a-timeline-item
          v-for="item in getRecordLogs"
          :key="item.id"
        >
          <div>
            <div
              class="timeline-header"
              style=""
            >
              <span>积分：</span>
              <span
                style="color: green"
                v-if="item.add_point"
              >
                + {{ item.add_point }}
              </span>
              <span
                style="color: red"
                v-if="item.remove_point"
              >
                - {{ item.remove_point }}
              </span>
              <span class="time">{{ item.created_at }}</span>
            </div>
            <div class="timeline-row">
              <div>剩余积分：{{ item.current_point }}</div>
              <div class="op-name">
                <template v-if="item.Admin"><img
                class="user-info-avatar"
                style=""
                :src="item.Admin.avatar"
                alt=""
              />
               {{ item.Admin.admin_name }}</template>
                <template v-else><img
                class="user-info-avatar"
                style=""
                :src="userInfo.avatar"
                alt=""
              />：{{ userInfo.user_name }}</template>
              </div>
            </div>

            <!-- {{ item.operation }} -->
          </div>

          <!-- <div>备注：{{ item.remark }}</div> -->
        </a-timeline-item>
      </a-timeline>
    </a-col>
  </a-row>

  <a-drawer
    title="操作积分"
    placement="right"
    :closable="true"
    width="800"
    :maskClosable="false"
    :keyboard="false"
    v-model:open="showAddDialog"
  >
    <a-divider>{{ openType == 1 ? '添加积分' : '消费积分' }}</a-divider>

    <a-form
      @finish="handleIntegralOk"
      :model="formState"
      :label-col="{ span: 4 }"
    >
      <a-form-item
        label="消费积分值"
        v-if="openType != 1"
        name="IntegralNumber"
        :rules="[{ required: true, message: '请输入积分值!' }]"
      >
        <a-input-number
          id="inputNumber"
          v-model:value="formState.IntegralNumber"
          :min="1"
          :max="9999999999999"
        />
      </a-form-item>
      <a-form-item
        label="选择消费的产品"
        name="productObj"
        v-if="openType == 1"
        :rules="[{ required: true, message: '请选择选择消费的产品' }]"
      >
        <a-select
          v-model:value="formState.productObj"
          label-in-value
          style="width: 120px"
          :options="prodOptions"
          :field-names="{ label: 'product_name', value: 'product_id' }"
        ></a-select>
      </a-form-item>
      <a-form-item
        label="积分备注"
        name="remark"
        :rules="[{ required: true, message: '请填写备注' }]"
      >
        <a-textarea
          :rows="4"
          v-model:value="formState.remark"
          placeholder="请输入备注"
          :maxlength="50"
        />
      </a-form-item>
      <a-form-item :wrapper-col="{ span: 14, offset: 4 }">
        <a-button
          html-type="submit"
          type="primary"
          :loading="btnloading"
        >
          确认
        </a-button>
      </a-form-item>
    </a-form>
  </a-drawer>
  <recordLog ref="recordLogRef"></recordLog>
</template>

<script setup>
import recordLog from './recordLog.vue'
  import { message } from 'ant-design-vue'
  import {
    productList,
    getUserDetail,
    getRecordPointList,
    getRecordAdd,
    getRecordConsume,
    getRecordLogList,
    getRecordDel
  } from '@/api/index'
  import { ref, reactive, toRefs, onMounted } from 'vue'
  import { useRoute } from 'vue-router'
  const route = useRoute()
  const userId = ref(null)
  const showAddDialog = ref(false)
  const activities = ref([])
  const pagination = reactive({
    current: 1,
    pageSize: 10,
    total: 0
  })
  const getRecordLogs = ref([])
 
  const formState = reactive({})
  const openType = ref('1')
  const columns = [
    { user_point_id: 'ID' },
    { uid: '用户' },
    { point: '剩余积分' },
    { remark: '备注' },
    { created_at: '时间' },
    { deleted_at: '状态' },
    { operator_name: '操作人' },

    {
      action: {
        title: '操作',
        width: '90px'
      }
    }
  ]
  const recordLogRef=ref(null)
  const btnloading = ref(false)
  const prodOptions = ref([])
  const getProductList = () => {
    productList().then((res) => {
      if (res.errorCode) {
        message.error(res.msg || '操作失败')
        return
      }
      prodOptions.value = res.data
    })
  }
  const goMoreLog = () => {
    recordLogRef.value.init(userId.value, userInfo.value)
  }
  getProductList()
  const handleTableChange = ({ current, pageSize }) => {
    pagination.current = current
    pagination.pageSize = pageSize
    getList()
  }
  // 积分扣减或者增加
  const handleIntegralOk = () => {
    let http = openType.value == '1' ? getRecordAdd : getRecordConsume
    let params = {
      uid: Number(userId.value),

      remark: formState.remark,
      operator_id: 1
    }

    if (openType.value == 1) {
      params.product = formState.productObj.option
    } else {
      params.point = formState.IntegralNumber
    }
    btnloading.value = true
    http(params)
      .then((res) => {
        if (res.errorCode) {
          message.error(res.msg || '操作失败')
          return
        }
        if (res.code == 200) {
          message.success('操作成功！')
          setTimeout(() => {
            getList()
          }, 1000)

          showAddDialog.value = false
        } else {
          message.error(res.msg)
        }
      })
      .catch((err) => {
        message.error(err.msg)
      })
      .finally((e) => {
        btnloading.value = false
      })
  }

  const record = ref({})

  const delText = ref('10s')
  const isdisabled = ref(true)
  const handleDel = (row) => {
    getRecordDel({
      uid: Number(userId.value),
      operator_id: 1
    })
      .then((res) => {
        if (res.errorCode) {
          message.error(res.msg || '操作失败')
          return
        }
        message.success('操作成功！')
        getList()
      })
      .catch((err) => {
        message.error(err.msg)
      })
  }
  const openPop = () => {
    let time = 3
    setInterval(() => {
      isdisabled.value = true
      delText.value = time + 's'
      time--
      if (time < 0) {
        isdisabled.value = false
        delText.value = '确定删除吗？'
        clearInterval()
      }
    }, 1000)
    // delText.value='确定删除吗？'
  }
  const openDialog = (type) => {
    showAddDialog.value = true
    openType.value = type
    formState.productObj = null
    ;(formState.IntegralNumber = null), (formState.remark = null)
  }
  const getList = () => {
    getRecordPointList({
      uid: userId.value,
      page: pagination.current,
      pageSize: pagination.pageSize
    }).then((res) => {
      if (res.errorCode) {
        message.error(res.msg || '操作失败')
        return
      }
      activities.value = res.data
      pagination.total = res.total
    })
    getRecordLogList({
      uid: userId.value,
      page:1,
      pageSize:10
    }).then((res) => {
      getRecordLogs.value = res.data
    })
  }
  const userInfo = ref(null)
  onMounted(() => {
    userId.value = route.query.id
    getUserDetail({ uid: userId.value }).then((res) => {
      if (res.errorCode) {
        message.error(res.msg || '操作失败')
        return
      }
      userInfo.value = res.data
    })
    getList()
  })
</script>
<style scoped lang="less">
  .box {
    display: flex;
  }
  .user-info {
    display: flex;
    align-items: center;
    justify-content: center;
    .user-info-avatar {
      width: 50px;
      height: 50px;
      border-radius: 50%;
      margin-right: 10px;
    }
  }
  .timeline-header {
    font-size: 18px;
    border-bottom: 1px solid #e5e5e5;
    padding-bottom: 5px;
    margin-bottom: 5px;
    display: flex;
    justify-content: flex-start;
    align-items: center;
    .time {
      margin-left: auto;
      font-size: 16px;
      margin-right: 60px;
    }
  }
  .timeline-row{
    display: flex;
    justify-content: space-between;
    align-items: center;
    .user-info-avatar{
      width: 30px;
      height: 30px;
    }
    .op-name{
      display: flex;
      align-items: center;
      margin-right: 60px;
    }
  }
</style>
